package com.ashlikun.zxing.analyze

import android.os.Handler
import com.ashlikun.camera.scan.analyze.Nv21Analyzer
import com.ashlikun.camera.scan.util.CameraXLogUtils
import com.ashlikun.zxing.util.LightHelper

/**
 * 作者　　: 李坤
 * 创建时间: 2024/2/21　16:00
 * 邮箱　　：496546144@qq.com
 *
 *
 * 功能介绍：环境光检查
 * @param onLightChange 回调在handler线程执行
 */
class LightAnalyzer(private val onLightChange: (isLight: Boolean) -> Unit) : Nv21Analyzer {
    private var handler: Handler? = null
    var enable = true

    //防止多次调用
    var bright: Boolean? = null
        private set
    private var darkCount = 0
    private var lightCount = 0
    fun setHandler(handler: Handler?) {
        this.handler = handler
    }

    override fun analyzeNv21(data: ByteArray, width: Int, height: Int): ByteArray {
        if (onLightChange != null && enable && handler != null) {
            handler!!.post {
                val avDark = LightHelper.getAvDark(data)
                if (avDark > STANDVALUES && (bright == null || !bright!!)) {
                    darkCount = 0
                    lightCount++
                    if (lightCount > MINCOUNT) {
                        CameraXLogUtils.e("亮 avDark = $avDark   darkCount = $darkCount    lightCount = $lightCount")
                        darkCount = 0
                        lightCount = 0
                        bright = true
                        onLightChange?.invoke(true)
                    }
                }
                if (avDark < STANDVALUES && (bright == null || bright!!)) {
                    lightCount = 0
                    darkCount++
                    if (darkCount > MINCOUNT) {
                        CameraXLogUtils.e("暗 avDark = $avDark   darkCount = $darkCount    lightCount = $lightCount")
                        darkCount = 0
                        lightCount = 0
                        bright = false
                        onLightChange?.invoke(false)
                    }
                }
            }
        }
        return data
    }

    companion object {
        //亮度临界值
        var STANDVALUES = 80

        //最小多少才能算
        var MINCOUNT = 4
    }
}
